﻿using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LightCAD.Core.Elements;
using LightCAD.Core;
using Avalonia.Controls;

namespace LightCAD.Runtime.Editor
{
    public static class LineDrawer
    {



        public static void DrawTo(this Line line, SKCanvas canvas, Vector2d offset)
        {
            //canvas.DrawPoint(new SKPoint(1, 1), ElementDrawer.defaultPen);
            //return;

            var start = ElementDrawer.PointWorldToScr(line.Start + offset);
            var end = ElementDrawer.PointWorldToScr(line.End + offset);
            //SKPathEffect effect = null;
            //if (line.IsSelected)
            //{
            //    effect = ElementDrawer.SelectedEffect;
            //}
            //using (var pen = new SKPaint { Color = SKColors.White, IsStroke = true, PathEffect = effect })
            //{
            //    canvas.DrawLine(start, end, pen);
            //}
            bool isDragCopy = (offset != Vector2d.Zero);
            var pen = ElementDrawer.GetDrawPen(line, isDragCopy);
            canvas.DrawLine(start, end, pen);
        }
        public static ControlGrip[] GetControlGrips(this Line line)
        {
            var grips = new List<ControlGrip>();
            var gripStart = new ControlGrip
            {
                Element = line,
                Name = "Start",
                Position = line.Start
            };
            grips.Add(gripStart);
            var gripEnd = new ControlGrip
            {
                Element = line,
                Name = "End",
                Position = line.End
            };
            grips.Add(gripEnd);
            return grips.ToArray();
        }

        private static string _gripName;
        private static Vector2d _position;
        private static Line _line;
        public static Action<SKCanvas> _SetDragGrip(this Line line, string gripName, Vector2d position, bool isEnd)
        {
            _line = line;
            if (!isEnd)
            {
                _gripName = gripName;
                _position = position;
                return DrawDragGrip;
            }
            else
            {
                if (gripName == "Start")
                    line.Set(start: position);
                else if (gripName == "End")
                {
                    _line.Set(end: position);
                }
                return null;
            }
        }

        public static void DrawDragGrip(SKCanvas canvas)
        {
            var start = ElementDrawer.PointWorldToScr(_line.Start);
            if (_gripName == "Start")
                start = ElementDrawer.PointWorldToScr(_position);

            var end = ElementDrawer.PointWorldToScr(_line.End);
            if (_gripName == "End")
                end = ElementDrawer.PointWorldToScr(_position);

            canvas.DrawLine(start, end, ElementDrawer.draggingPen);
        }

    }

}
